package nathizm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import com.google.gdata.client.blogger.BloggerService;
import com.google.gdata.data.Entry;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.ServiceException;

public class Upload extends Blogger {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) {

		File dir = new File(
				System.getProperty(Global.ENTRY_FOLDER_KEY) + "\\update");
		File[] files = dir.listFiles();

		try {

			BloggerService myService = getService();

			for (File file : files) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						new FileInputStream(file)));
				StringBuffer sb = new StringBuffer();
				int c;
				while ((c = br.read()) != -1) {
					sb.append((char) c);
				}

				String entryId = file.toString().split("_")[2];
				entryId = entryId.substring(0, entryId.length() - 4);

				URL editUrl = new URL(FEED_URI + Blogger.POSTS_FEED_URI_SUFFIX
						+ "/" + entryId);
				Entry entry = myService.getEntry(editUrl, Entry.class);

				int startIndex = sb.indexOf("<a name='more'></a>");
				if (startIndex >= 0){
					sb.replace(startIndex, startIndex + 19, "<!-- more -->");
				}
				
				HtmlTextConstruct html = new HtmlTextConstruct();
				html.setHtml(sb.toString());
				entry.setContent(html);
				String newTitle = file.toString().split("_")[1];
				entry.setTitle(new PlainTextConstruct(newTitle));

				myService.update(editUrl, entry);
			}

		} catch (ServiceException se) {
			se.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

}
